package com.dxy.netty.tcppackagesolve;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;

/**
 * @Description "头部包含数据包长度"方式解决粘包拆包问题-netty客户端
 * @Author dangxianyue
 * @Date 2023/1/8 22:09
 */
public class ProtocolNettyClient {

    private final String host;
    private final int port;

    public ProtocolNettyClient(String host, int port) {
        this.host = host;
        this.port = port;
    }

    public static void main(String[] args) {
        try {
            new ProtocolNettyClient("localhost", 8089).run();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    public void run() throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ProtocolNettyClientInitializer());  // 自定义一个初始化类
            // 连接服务器
            ChannelFuture channelFuture = bootstrap.connect(this.host, this.port).sync();
            channelFuture.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }

    static class ProtocolNettyClientInitializer extends ChannelInitializer<SocketChannel> {
        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();

            //这里使用自定义分隔符
            ByteBuf delimiter = Unpooled.copiedBuffer("\r\n".getBytes());
            pipeline.addFirst(new DelimiterBasedFrameDecoder(8192, delimiter));

            // 添加出站处理器- 协议报文转字节以便网络传输
            pipeline.addLast(new ProtocolMessageEncoder());
            // 添加入站解码器-把字节转为协议报文对象以便业务逻辑处理
            pipeline.addLast(new ProtocolMessageDecoder());

            // 添加一个自定义handler，处理业务逻辑
            pipeline.addLast(new ProtocolNettyClientHandler());
        }
    }
}
